import { getInfo, updateUserInfo, uploadImg } from '../../services/profile'
import { checkIfLogin } from '../../utils/check'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{},
    showChangeSex: false,
    useSexColumns:['男', '女'],
    currentSex:'',
    tempSex:'',
    hasUserInfo: false,
    token:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    checkIfLogin()
    this.handleGetInfo()
    this.setData({
      token: wx.getStorageSync('token')
    })
  },

  async handleGetInfo(){
    let InfoRes = await getInfo()
    if(InfoRes.code === 200){
      let currentSex = ""
      let hasUserInfo = false
      if(InfoRes.user.sex == 0){
        currentSex = '男'
      }
      if(InfoRes.user.sex == 1){
        currentSex = '女'
      }
      if(InfoRes.user.avatar){
        hasUserInfo = true
      }
      this.setData({
        userInfo: InfoRes.user,
        currentSex,
        hasUserInfo
      })
    }
  },

  // 头像
  navToAvatar(){
    if(this.data.hasUserInfo){
      return
    }
    this.getUserProfile()
  },

  handleScanAvatar(){
    const _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const fs = wx.getFileSystemManager()
        fs.readFile({
          filePath: res.tempFiles[0].tempFilePath,
          encoding: 'base64',
          success(readRes){
            uploadImg(readRes.data).then(picRes => {
              if(picRes.code === 200){
                let avatar = picRes.msg
                _this.setData({
                  ['userInfo.avatar']: avatar
                })
                _this.handleUpdateInfo({
                  avatar
                })               
              }
            })
          } 
        })
      }
    })
  },

  getUserProfile() {
    console.log("112212")
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log("res>>>", res)
        let userInfo = {...this.data.userInfo, ...res.userInfo}
        userInfo.avatar = res.userInfo.avatarUrl
        let avatar = res.userInfo.avatarUrl
        let nickName = res.userInfo.nickName
        this.setData({
          userInfo,
          hasUserInfo: true
        })
        this.handleUpdateInfo({
          avatar,
          nickName
        })
      }
    })
  },


  // 修改昵称
  onChangeNickName(event){
    let nickName = event.detail
    this.handleUpdateInfo({
      nickName,
    })
  },

  // 修改性别
  navToSex(){
    this.setData({
      showChangeSex: true
    })
  },
  onChangeUseSex(info){
    let tempSex = info.detail.value
    this.setData({
      tempSex
    })
  },
  onCancelUseSex(){
    this.setData({
      showChangeSex: false
    })
  },
  onConfirmUseSex(){
    let currentSex = this.data.tempSex
    let sex = 2
    if(currentSex == '男'){
      sex = 0
    } else if(currentSex == '女'){
      sex = 1
    }
    this.setData({
      showChangeSex: false,
      currentSex,
      ['userInfo.sex']: sex
    })
    this.handleUpdateInfo({
      sex,
    })
  },

  // 修改邮箱
  onChangeEmail(event){
    let email = event.detail
    this.handleUpdateInfo({
      email,
    })
  },

  async handleUpdateInfo(info = {}){
    let dataInfo = {
      userId: this.data.userInfo.userId,
      userName: this.data.userInfo.userName,
      ...info
    }

    let updateRes = await updateUserInfo(dataInfo)
    console.log("updateRes>>>", updateRes)
  }
})